package com.fundcrawler.service;

import cn.hutool.core.collection.CollectionUtil;
import com.fundcrawler.common.Constants;
import com.fundcrawler.entity.BizParam;
import com.fundcrawler.entity.FundNav;
import com.fundcrawler.service.manager.BizParamManager;
import com.fundcrawler.service.manager.FundNavManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DataService {

    @Autowired
    private FundNavManager fundNavManager;

    public Map<String, Object> getSummary() {
        Map<String, Object> summary = new HashMap<>();
        summary.put("totalFunds", fundNavManager.countDistinctFundCodes());
        summary.put("totalRecords", fundNavManager.count());
        return summary;
    }

    public List<FundNav> getRecentNavs(String fundCode, int days) {
        return fundNavManager.findByFundCode(fundCode, PageRequest.of(0, days)).getContent();
    }

    public List<FundNav> getAllData() {
        return fundNavManager.findAll();
    }

    @Autowired
    private FundCrawlerAspxService crawler;
    @Autowired
    private BizParamManager bizParamManager;

    public void updateAllFunds() {
        // biz_param配置要监控的基金代码
        List<BizParam> list = bizParamManager.findAllByParamCode(Constants.FUND_NAME);
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        List<String> FUND_CODES = list.stream().map(BizParam::getParamGroup).collect(Collectors.toList());
        for (String code : FUND_CODES) {
            log.info("🔍 开始爬取基金: {}", code);
            try {
                crawler.crawlFundHistory(code);
            } catch (Exception e) {
                log.error("爬取基金异常：", e);
            }
        }
    }


}
